package crl.lottery.model
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	
	import crl.lottery.model.vo.ItemVO;
	
	public class LogicConfig extends EventDispatcher
	{
		public static var lottery_result_url:String;
		public static var lottery_start_url:String;
		
		private var dataList:Dictionary;
		private var loader:URLLoader;
		
		public function LogicConfig()
		{
		}
		
		public function load(path:String):void{
			loader=new URLLoader();
			loader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			loader.addEventListener(Event.COMPLETE,completeHandler);
			loader.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			loader.load(new URLRequest(path));
		}
		
		private function progressHandler(event:ProgressEvent):void{
			this.dispatchEvent(event.clone());
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void{
			this.error(event.text);
		}
		
		/**
		 * 数据加载完成时; 
		 * @param event
		 * 
		 */		
		private function completeHandler(event:Event):void{
			var xml:XML;
			try{
				xml=new XML((event.target as URLLoader).data);
				
				var code:int=parseInt(xml.code);
				if(code==100){
					this.error(xml.message)
					return;
				}
				
			}catch(e:Error){
				this.error(e.message);
			}
			
			
			dataList=new Dictionary();
			
			var list:XMLList=xml.descendants("name");
			
			var itemvo:ItemVO;
			for each(var item:XML in list){
				itemvo=new ItemVO();
				itemvo.bindXML(item);
				
				dataList[itemvo.order]=itemvo;
			}
			
			this.dispatchEvent(event);
		}
		
		public function getList():Vector.<ItemVO>{
			var vector:Vector.<ItemVO>=new Vector.<ItemVO>();
			for each(var item:ItemVO in dataList){
				vector.push(item);
			}
			return vector;
		}
		
		public function getItemByKey(key:int):ItemVO{
			return this.dataList[key];
		}
		
		/**
		 * 错误提出; 
		 * @param value
		 * 
		 */		
		private function error(value:String):void{
			this.dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false,false,value));
		}
		
	}
}